// 图片懒加载
import Vue from "vue"

const lazyDirective = (el, binding) => {
    if(el.localName !== 'img'){
        throw new Error('lazy指令只能在img标签上使用')
    }
    el.src = "" //将渲染的src赋为空，则不会渲染图片出来
    let observer = new IntersectionObserver(async ([{ isIntersecting }]) => { // 调用方法得到该elDOM元素是否处于可视区域
        if (isIntersecting) { //回调是否处于可视区域，true or false
            if (binding.value.img_url) {
                el.src = binding.value.img_url
            } else {
                let id = binding.value.img_id
                let request = binding.value.requestFun
                try {
                    let res = await request(id)
                    el.src = res.data.url
                } catch (err) {
                    console.log(err)
                    el.src = ""
                }
            }
            observer.unobserve(el) // 只需要监听一次即可，第二次滑动到可视区域时候不在监听
        }
    })
    observer.observe(el) // 调用方法
}

export const setupLazyDirective = () => {
    Vue.directive('lazy', {
        inserted: lazyDirective,
    })
}
